package org.example.myleet.p677;

import org.example.myleet.Utils.Assert;
import org.example.myleet.Utils.JsonUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Assert.isTrue(Assert.isPass(
                parse1DIntegerArray("[null, null, 3, null, 5, null, 6]"),
                execute("[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\", \"insert\", \"sum\"]", "[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"], [\"app\", 3], [\"ap\"]]")));
    }

    private static List<Integer> execute(String input1, String input2) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        List<String> steps = parse1DStringArray(input1);
        List<List<Object>> params = parse2DArray(input2);
        List<Integer> result = new ArrayList<>();
        result.add(null);
        MapSum map = new MapSum();
        for (int i = 1; i < steps.size(); ++i) {
            List<Object> param = params.get(i);
            if ("insert".equals(steps.get(i))) {
                Method m = map.getClass().getMethod(steps.get(i), String.class, int.class);
                result.add((Integer) m.invoke(map, param.get(0), param.get(1)));
            } else {
                Method m = map.getClass().getMethod(steps.get(i), String.class);
                result.add((Integer) m.invoke(map, param.get(0)));
            }
        }
        return result;
    }

    private static List<List<Object>> parse2DArray(String input) {
        return JsonUtils.parse(input, List.class);
    }

    private static List<Integer> parse1DIntegerArray(String input) {
        return JsonUtils.parse(input, List.class);
    }

    private static List<String> parse1DStringArray(String input) {
        return JsonUtils.parse(input, List.class);
    }
}
